package com.promise.jokerdream.viewmodel

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.promise.jokerdream.config.user.UserConfig
import com.promise.jokerdream.model.formation.FormationSelection
import com.promise.jokerdream.model.swordfight.SwordFightKnightItem
import com.promise.jokerdream.config.game.MercenaryTaskType
import com.promise.jokerdream.config.game.WulinRegistrationType
import com.promise.jokerdream.config.game.WlmzGroundType
import com.promise.jokerdream.config.game.ImmortalType
import com.promise.jokerdream.config.game.EscortGameConfig
import com.promise.jokerdream.config.game.EscortStrategy
import com.promise.jokerdream.config.game.ExperiencePriorityType
import com.promise.jokerdream.config.game.AscendHeavenGameMode
import com.promise.jokerdream.config.game.KnightArenaFormation
import com.promise.jokerdream.database.UserDataManager
import com.promise.jokerdream.database.account.UserAccount
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class SettingsViewModel(application: Application) : AndroidViewModel(application) {
    
    private val userDataManager = UserDataManager.getInstance(application)
    
    private val _account = MutableStateFlow<UserAccount?>(null)
    val account: StateFlow<UserAccount?> = _account.asStateFlow()
    
    private val _userConfig = MutableStateFlow<UserConfig?>(null)
    val userConfig: StateFlow<UserConfig?> = _userConfig.asStateFlow()
    
    init {
        loadCurrentAccount()
    }
    
    private fun loadCurrentAccount() {
        viewModelScope.launch {
            val currentAccount = userDataManager.getCurrentAccount()
            _account.value = currentAccount
            _userConfig.value = currentAccount?.config
        }
    }
    
    fun saveConfig(newConfig: UserConfig) {
        viewModelScope.launch {
            _userConfig.value = newConfig
            _account.value?.let { currentAccount ->
                val updatedAccount = currentAccount.copy(config = newConfig)
                _account.value = updatedAccount
                userDataManager.saveUserAccount(updatedAccount)
            }
        }
    }
    
    // 刮刮卡配置更新
    fun updateScratchConfig(
        enabledSetting: Boolean? = null,
        dailyScratchEnabled: Boolean? = null,
        hourlyScratchEnabled: Boolean? = null
    ) {
        val currentConfig = _userConfig.value ?: return
        val newConfig = currentConfig.copy(
            gameConfig = currentConfig.gameConfig.copy(
                scratchConfig = currentConfig.gameConfig.scratchConfig.copy(
                    enabledSetting = enabledSetting ?: currentConfig.gameConfig.scratchConfig.enabledSetting,
                    dailyScratchEnabled = dailyScratchEnabled ?: currentConfig.gameConfig.scratchConfig.dailyScratchEnabled,
                    hourlyScratchEnabled = hourlyScratchEnabled ?: currentConfig.gameConfig.scratchConfig.hourlyScratchEnabled
                )
            )
        )
        saveConfig(newConfig)
    }
    
    // 深渊之潮配置更新
    fun updateAbyssConfig(
        enabledSetting: Boolean? = null,
        wishPointsEnabled: Boolean? = null,
        exchangeTimesEnabled: Boolean? = null,
        challengeEnabled: Boolean? = null,
        reviveEnabled: Boolean? = null,
        selectedAbyssText: String? = null
    ) {
        val currentConfig = _userConfig.value ?: return
        val newConfig = currentConfig.copy(
            gameConfig = currentConfig.gameConfig.copy(
                abyssConfig = currentConfig.gameConfig.abyssConfig.copy(
                    enabledSetting = enabledSetting ?: currentConfig.gameConfig.abyssConfig.enabledSetting,
                    wishPointsEnabled = wishPointsEnabled ?: currentConfig.gameConfig.abyssConfig.wishPointsEnabled,
                    exchangeTimesEnabled = exchangeTimesEnabled ?: currentConfig.gameConfig.abyssConfig.exchangeTimesEnabled,
                    challengeEnabled = challengeEnabled ?: currentConfig.gameConfig.abyssConfig.challengeEnabled,
                    reviveEnabled = reviveEnabled ?: currentConfig.gameConfig.abyssConfig.reviveEnabled,
                    selectedAbyssText = selectedAbyssText ?: currentConfig.gameConfig.abyssConfig.selectedAbyssText
                )
            )
        )
        saveConfig(newConfig)
    }
    
    // 乐斗配置更新
    fun updatePenguinFightConfig(
        enabledSetting: Boolean? = null,
        bossEnabled: Boolean? = null,
        xialvEnabled: Boolean? = null,
        shituEnabled: Boolean? = null,
        jiebaiEnabled: Boolean? = null
    ) {
        val currentConfig = _userConfig.value ?: return
        val newConfig = currentConfig.copy(
            gameConfig = currentConfig.gameConfig.copy(
                penguinFightConfig = currentConfig.gameConfig.penguinFightConfig.copy(
                    enabledSetting = enabledSetting ?: currentConfig.gameConfig.penguinFightConfig.enabledSetting,
                    bossEnabled = bossEnabled ?: currentConfig.gameConfig.penguinFightConfig.bossEnabled,
                    marryEnabled = xialvEnabled ?: currentConfig.gameConfig.penguinFightConfig.marryEnabled,
                    shituEnabled = shituEnabled ?: currentConfig.gameConfig.penguinFightConfig.shituEnabled,
                    brotherEnabled = jiebaiEnabled ?: currentConfig.gameConfig.penguinFightConfig.brotherEnabled
                )
            )
        )
        saveConfig(newConfig)
    }
    
    // 十二宫配置更新
    fun updateConstellationConfig(
        enabledSetting: Boolean? = null,
        levelName: String? = null
    ) {
        val currentConfig = _userConfig.value ?: return
        val newConfig = currentConfig.copy(
            gameConfig = currentConfig.gameConfig.copy(
                constellationConfig = currentConfig.gameConfig.constellationConfig.copy(
                    enabledSetting = enabledSetting ?: currentConfig.gameConfig.constellationConfig.enabledSetting,
                    levelName = levelName ?: currentConfig.gameConfig.constellationConfig.levelName
                )
            )
        )
        saveConfig(newConfig)
    }
    
    // 历练配置更新
    fun updateExperienceConfig(
        enabledSetting: Boolean? = null,
        priorityType: com.promise.jokerdream.config.game.ExperiencePriorityType? = null,
        customOrder: List<Int>? = null,
        useVitalityPotion: Boolean? = null
    ) {
        val currentConfig = _userConfig.value ?: return
        val newConfig = currentConfig.copy(
            gameConfig = currentConfig.gameConfig.copy(
                experienceConfig = currentConfig.gameConfig.experienceConfig.copy(
                    enabledSetting = enabledSetting ?: currentConfig.gameConfig.experienceConfig.enabledSetting,
                    priorityType = (priorityType?.name ?: currentConfig.gameConfig.experienceConfig.priorityType),
                    customOrder = (customOrder?.joinToString(",") ?: currentConfig.gameConfig.experienceConfig.customOrder),
                    useVitalityPotion = useVitalityPotion ?: currentConfig.gameConfig.experienceConfig.useVitalityPotion
                )
            )
        )
        saveConfig(newConfig)
    }
    
    // 幻境配置更新
    fun updateMistyConfig(
        enabledSetting: Boolean? = null,
        selectedMistyText: String? = null
    ) {
        val currentConfig = _userConfig.value ?: return
        val newConfig = currentConfig.copy(
            gameConfig = currentConfig.gameConfig.copy(
                mistyConfig = currentConfig.gameConfig.mistyConfig.copy(
                    enabledSetting = enabledSetting ?: currentConfig.gameConfig.mistyConfig.enabledSetting,
                    selectedMistyText = selectedMistyText ?: currentConfig.gameConfig.mistyConfig.selectedMistyText
                )
            )
        )
        saveConfig(newConfig)
    }
    
    // 商会配置更新
    fun updateFactionCommerceConfig(
        enabledSetting: Boolean? = null,
        treasureBoxEnabled: Boolean? = null,
        tradingEnabled: Boolean? = null,
        selectedTradingRewards: List<String>? = null,
        exchangeEnabled: Boolean? = null,
        selectedExchangeRewards: List<String>? = null
    ) {
        val currentConfig = _userConfig.value ?: return
        val newConfig = currentConfig.copy(
            gameConfig = currentConfig.gameConfig.copy(
                factionCommerceConfig = currentConfig.gameConfig.factionCommerceConfig.copy(
                    enabledSetting = enabledSetting ?: currentConfig.gameConfig.factionCommerceConfig.enabledSetting,
                    treasureBoxEnabled = treasureBoxEnabled ?: currentConfig.gameConfig.factionCommerceConfig.treasureBoxEnabled,
                    tradingEnabled = tradingEnabled ?: currentConfig.gameConfig.factionCommerceConfig.tradingEnabled,
                    selectedTradingRewards = (selectedTradingRewards?.joinToString(",") ?: currentConfig.gameConfig.factionCommerceConfig.selectedTradingRewards),
                    exchangeEnabled = exchangeEnabled ?: currentConfig.gameConfig.factionCommerceConfig.exchangeEnabled,
                    selectedExchangeRewards = (selectedExchangeRewards?.joinToString(",") ?: currentConfig.gameConfig.factionCommerceConfig.selectedExchangeRewards)
                )
            )
        )
        saveConfig(newConfig)
    }
    
    // 帮派供奉配置更新
    fun updateFactionFeedDemoConfig(
        enabledSetting: Boolean? = null,
        feedItemName: String? = null
    ) {
        val currentConfig = _userConfig.value ?: return
        val newConfig = currentConfig.copy(
            gameConfig = currentConfig.gameConfig.copy(
                factionFeedDemoConfig = currentConfig.gameConfig.factionFeedDemoConfig.copy(
                    enabledSetting = enabledSetting ?: currentConfig.gameConfig.factionFeedDemoConfig.enabledSetting,
                    feedItemName = feedItemName ?: currentConfig.gameConfig.factionFeedDemoConfig.feedItemName
                )
            )
        )
        saveConfig(newConfig)
    }
    
    // 飞升配置更新
    fun updateAscendHeavenConfig(
        enabledSetting: Boolean? = null,
        gameMode: AscendHeavenGameMode? = null,
        scheduledChallengeEnabled: Boolean? = null,
        registrationTime: String? = null
    ) {
        val currentConfig = _userConfig.value ?: return
        val newConfig = currentConfig.copy(
            gameConfig = currentConfig.gameConfig.copy(
                ascendHeavenConfig = currentConfig.gameConfig.ascendHeavenConfig.copy(
                    enabledSetting = enabledSetting ?: currentConfig.gameConfig.ascendHeavenConfig.enabledSetting,
                    gameMode = (gameMode?.name ?: currentConfig.gameConfig.ascendHeavenConfig.gameMode),
                    scheduledChallengeEnabled = scheduledChallengeEnabled ?: currentConfig.gameConfig.ascendHeavenConfig.scheduledChallengeEnabled,
                    registrationTime = registrationTime ?: currentConfig.gameConfig.ascendHeavenConfig.registrationTime
                )
            )
        )
        saveConfig(newConfig)
    }
    
    // 武林配置更新
    fun updateWulinConfig(
        enabledSetting: Boolean? = null,
        registrationType: WulinRegistrationType? = null
    ) {
        val currentConfig = _userConfig.value ?: return
        val newConfig = currentConfig.copy(
            gameConfig = currentConfig.gameConfig.copy(
                wulinConfig = currentConfig.gameConfig.wulinConfig.copy(
                    enabledSetting = enabledSetting ?: currentConfig.gameConfig.wulinConfig.enabledSetting,
                    registrationType = (registrationType?.name ?: currentConfig.gameConfig.wulinConfig.registrationType)
                )
            )
        )
        saveConfig(newConfig)
    }
    
    // 佣兵派遣配置更新
    fun updateMercenaryDispatchConfig(
        enabledSetting: Boolean? = null,
        selectedTaskTypes: Set<MercenaryTaskType>? = null
    ) {
        val currentConfig = _userConfig.value ?: return
        val currentMercenaryConfig = currentConfig.gameConfig.mercenaryDispatchConfig
        
        val newConfig = currentConfig.copy(
            gameConfig = currentConfig.gameConfig.copy(
                mercenaryDispatchConfig = currentMercenaryConfig.copy(
                    enabledSetting = enabledSetting ?: currentMercenaryConfig.enabledSetting,
                    selectedTaskTypes = (selectedTaskTypes?.joinToString(",") { it.name } ?: currentMercenaryConfig.selectedTaskTypes)
                )
            )
        )
        saveConfig(newConfig)
    }
    
    // 仙武配置更新
    fun updateImmortalsConfig(
        enabledSetting: Boolean? = null,
        selectedImmortalType: ImmortalType? = null
    ) {
        val currentConfig = _userConfig.value ?: return
        val newConfig = currentConfig.copy(
            gameConfig = currentConfig.gameConfig.copy(
                immortalsConfig = currentConfig.gameConfig.immortalsConfig.copy(
                    enabledSetting = enabledSetting ?: currentConfig.gameConfig.immortalsConfig.enabledSetting,
                    selectedImmortalType = (selectedImmortalType?.name ?: currentConfig.gameConfig.immortalsConfig.selectedImmortalType)
                )
            )
        )
        saveConfig(newConfig)
    }
    
    // 侠客岛任务配置更新
    fun updateKnightMissionConfig(
        enabledSetting: Boolean? = null,
        selectedKnightRewards: List<String>? = null
    ) {
        val currentConfig = _userConfig.value ?: return
        val newConfig = currentConfig.copy(
            gameConfig = currentConfig.gameConfig.copy(
                knightMissionConfig = currentConfig.gameConfig.knightMissionConfig.copy(
                    enabledSetting = enabledSetting ?: currentConfig.gameConfig.knightMissionConfig.enabledSetting,
                    selectedKnightRewards = (selectedKnightRewards?.joinToString(",") ?: currentConfig.gameConfig.knightMissionConfig.selectedKnightRewards)
                )
            )
        )
        saveConfig(newConfig)
    }
    
    // 世界树配置更新
    fun updateWorldTreeConfig(
        enabledSetting: Boolean? = null,
        collectMaterialsEnabled: Boolean? = null,
        feedingEnabled: Boolean? = null
    ) {
        val currentConfig = _userConfig.value ?: return
        val newConfig = currentConfig.copy(
            gameConfig = currentConfig.gameConfig.copy(
                worldTreeConfig = currentConfig.gameConfig.worldTreeConfig.copy(
                    enabledSetting = enabledSetting ?: currentConfig.gameConfig.worldTreeConfig.enabledSetting,
                    collectMaterialsEnabled = collectMaterialsEnabled ?: currentConfig.gameConfig.worldTreeConfig.collectMaterialsEnabled,
                    feedingEnabled = feedingEnabled ?: currentConfig.gameConfig.worldTreeConfig.feedingEnabled
                )
            )
        )
        saveConfig(newConfig)
    }
    
    // 侠士配置更新
    fun updateKnightConfig(
        enabledSetting: Boolean? = null,
        collectRewardsEnabled: Boolean? = null,
        exchangeItemsEnabled: Boolean? = null,
        selectedExchangeItems: List<String>? = null
    ) {
        val currentConfig = _userConfig.value ?: return
        val newConfig = currentConfig.copy(
            gameConfig = currentConfig.gameConfig.copy(
                knightConfig = currentConfig.gameConfig.knightConfig.copy(
                    enabledSetting = enabledSetting ?: currentConfig.gameConfig.knightConfig.enabledSetting,
                    collectRewardsEnabled = collectRewardsEnabled ?: currentConfig.gameConfig.knightConfig.collectRewardsEnabled,
                    exchangeItemsEnabled = exchangeItemsEnabled ?: currentConfig.gameConfig.knightConfig.exchangeItemsEnabled,
                    selectedExchangeItems = (selectedExchangeItems?.joinToString(",") ?: currentConfig.gameConfig.knightConfig.selectedExchangeItems)
                )
            )
        )
        saveConfig(newConfig)
    }
    
    // 竞技场配置更新
    fun updateArenaConfig(
        enabledSetting: Boolean? = null,
        scheduledChallengeEnabled: Boolean? = null,
        registrationTime: String? = null
    ) {
        val currentConfig = _userConfig.value ?: return
        val newConfig = currentConfig.copy(
            gameConfig = currentConfig.gameConfig.copy(
                arenaConfig = currentConfig.gameConfig.arenaConfig.copy(
                    enabledSetting = enabledSetting ?: currentConfig.gameConfig.arenaConfig.enabledSetting,
                    scheduledChallengeEnabled = scheduledChallengeEnabled ?: currentConfig.gameConfig.arenaConfig.scheduledChallengeEnabled,
                    registrationTime = registrationTime ?: currentConfig.gameConfig.arenaConfig.registrationTime
                )
            )
        )
        saveConfig(newConfig)
    }

    // 侠士论剑配置更新
    fun updateKnightArenaConfig(
        enabledSetting: Boolean? = null,
        scheduledChallengeEnabled: Boolean? = null,
        registrationTime: String? = null,
        formations: List<KnightArenaFormation>? = null,
    ) {
        val currentConfig = _userConfig.value ?: return
        val newConfig = currentConfig.copy(
            gameConfig = currentConfig.gameConfig.copy(
                knightArenaConfig = currentConfig.gameConfig.knightArenaConfig.copy(
                    enabledSetting = enabledSetting ?: currentConfig.gameConfig.knightArenaConfig.enabledSetting,
                    scheduledChallengeEnabled = scheduledChallengeEnabled ?: currentConfig.gameConfig.knightArenaConfig.scheduledChallengeEnabled,
                    registrationTime = registrationTime ?: currentConfig.gameConfig.knightArenaConfig.registrationTime,
                    formationsJson = (formations?.let { 
                        val json = kotlinx.serialization.json.Json { ignoreUnknownKeys = true; encodeDefaults = true }
                        json.encodeToString(kotlinx.serialization.serializer<List<com.promise.jokerdream.config.game.KnightArenaFormation>>(), it)
                    } ?: currentConfig.gameConfig.knightArenaConfig.formationsJson)
                )
            )
        )
        saveConfig(newConfig)
    }
    
    // 门派配置更新
    fun updateSectConfig(
        enabledSetting: Boolean? = null,
        paidIncenseEnabled: Boolean? = null,
        paidMemberTrainingEnabled: Boolean? = null
    ) {
        val currentConfig = _userConfig.value ?: return
        val newConfig = currentConfig.copy(
            gameConfig = currentConfig.gameConfig.copy(
                sectConfig = currentConfig.gameConfig.sectConfig.copy(
                    enabledSetting = enabledSetting ?: currentConfig.gameConfig.sectConfig.enabledSetting,
                    paidIncenseEnabled = paidIncenseEnabled ?: currentConfig.gameConfig.sectConfig.paidIncenseEnabled,
                    paidMemberTrainingEnabled = paidMemberTrainingEnabled ?: currentConfig.gameConfig.sectConfig.paidMemberTrainingEnabled
                )
            )
        )
        saveConfig(newConfig)
    }
    
    // 押镖配置更新
    fun updateEscortConfig(
        enabledSetting: Boolean? = null,
        selectedNpcIds: List<Int>? = null,
        strategy: EscortStrategy? = null
    ) {
        val currentConfig = _userConfig.value ?: return
        val newConfig = currentConfig.copy(
            gameConfig = currentConfig.gameConfig.copy(
                escortConfig = currentConfig.gameConfig.escortConfig.copy(
                    enabledSetting = enabledSetting ?: currentConfig.gameConfig.escortConfig.enabledSetting,
                    selectedNpcIds = (selectedNpcIds?.joinToString(",") ?: currentConfig.gameConfig.escortConfig.selectedNpcIds),
                    strategy = (strategy?.name ?: currentConfig.gameConfig.escortConfig.strategy)
                )
            )
        )
        saveConfig(newConfig)
    }
    
    // 武林盟主配置更新
    fun updateWlmzConfig(
        enabledSetting: Boolean? = null,
        groundType: WlmzGroundType? = null
    ) {
        val currentConfig = _userConfig.value ?: return
        val newConfig = currentConfig.copy(
            gameConfig = currentConfig.gameConfig.copy(
                wlmzConfig = currentConfig.gameConfig.wlmzConfig.copy(
                    enabledSetting = enabledSetting ?: currentConfig.gameConfig.wlmzConfig.enabledSetting,
                    groundType = (groundType?.name ?: currentConfig.gameConfig.wlmzConfig.groundType)
                )
            )
        )
        saveConfig(newConfig)
    }
    
    // 佣兵助阵配置更新
    fun updateFormationConfig(
        enabledSetting: Boolean? = null,
        selectedTypeId: Int? = null,
        selectedTypeName: String? = null,
        selectedFormationId: Int? = null,
        selectedFormationName: String? = null,
        selectedAttrIndex: Int? = null,
        selectedAttrName: String? = null
    ) {
        val currentConfig = _userConfig.value ?: return
        val currentFormationConfig = currentConfig.gameConfig.formationConfig
        
        // 从 JSON 解析当前选择信息
        val currentSelection = if (currentFormationConfig.selectionJson.isEmpty()) {
            FormationSelection.EMPTY
        } else {
            try {
                val json = kotlinx.serialization.json.Json { ignoreUnknownKeys = true; encodeDefaults = true }
                json.decodeFromString<FormationSelection>(currentFormationConfig.selectionJson)
            } catch (e: Exception) {
                FormationSelection.EMPTY
            }
        }
        
        // 构建新的选择信息
        val newSelection = if (selectedTypeId != null || selectedFormationId != null || selectedAttrIndex != null) {
            FormationSelection(
                selectedTypeId = selectedTypeId ?: currentSelection.selectedTypeId,
                selectedTypeName = selectedTypeName ?: currentSelection.selectedTypeName,
                selectedFormationId = selectedFormationId ?: currentSelection.selectedFormationId,
                selectedFormationName = selectedFormationName ?: currentSelection.selectedFormationName,
                selectedAttrIndex = selectedAttrIndex ?: currentSelection.selectedAttrIndex,
                selectedAttrName = selectedAttrName ?: currentSelection.selectedAttrName
            )
        } else {
            currentSelection
        }
        
        // 将新选择信息序列化为 JSON
        val newSelectionJson = try {
            val json = kotlinx.serialization.json.Json { ignoreUnknownKeys = true; encodeDefaults = true }
            json.encodeToString(kotlinx.serialization.serializer<FormationSelection>(), newSelection)
        } catch (e: Exception) {
            ""
        }
        
        val newConfig = currentConfig.copy(
            gameConfig = currentConfig.gameConfig.copy(
                formationConfig = currentFormationConfig.copy(
                    enabledSetting = enabledSetting ?: currentFormationConfig.enabledSetting,
                    selectionJson = newSelectionJson
                )
            )
        )
        saveConfig(newConfig)
    }
    
    // 其他配置更新
    fun updateOtherConfig(
        enabledSetting: Boolean? = null,
        dreamTripEnabled: Boolean? = null,
        penguinTravelogueEnabled: Boolean? = null,
        factionChallengeEnabled: Boolean? = null,
        factionAltarEnabled: Boolean? = null,
        scrollDungeonEnabled: Boolean? = null,
        factionMineEnabled: Boolean? = null,
        penguinRecallEnabled: Boolean? = null,
        apprenticeExperienceEnabled: Boolean? = null
    ) {
        val currentConfig = _userConfig.value ?: return
        val newConfig = currentConfig.copy(
            gameConfig = currentConfig.gameConfig.copy(
                otherConfig = currentConfig.gameConfig.otherConfig.copy(
                    enabledSetting = enabledSetting ?: currentConfig.gameConfig.otherConfig.enabledSetting,
                    dreamTripEnabled = dreamTripEnabled ?: currentConfig.gameConfig.otherConfig.dreamTripEnabled,
                    penguinTravelogueEnabled = penguinTravelogueEnabled ?: currentConfig.gameConfig.otherConfig.penguinTravelogueEnabled,
                    factionChallengeEnabled = factionChallengeEnabled ?: currentConfig.gameConfig.otherConfig.factionChallengeEnabled,
                    factionAltarEnabled = factionAltarEnabled ?: currentConfig.gameConfig.otherConfig.factionAltarEnabled,
                    scrollDungeonEnabled = scrollDungeonEnabled ?: currentConfig.gameConfig.otherConfig.scrollDungeonEnabled,
                    factionMineEnabled = factionMineEnabled ?: currentConfig.gameConfig.otherConfig.factionMineEnabled,
                    penguinRecallEnabled = penguinRecallEnabled ?: currentConfig.gameConfig.otherConfig.penguinRecallEnabled,
                    apprenticeExperienceEnabled = apprenticeExperienceEnabled ?: currentConfig.gameConfig.otherConfig.apprenticeExperienceEnabled
                )
            )
        )
        saveConfig(newConfig)
    }
    
    // 货币兑换配置更新
    fun updateCurrencyExchangeConfig(
        enabledSetting: Boolean? = null,
        currencyExchangeAmount: com.promise.jokerdream.model.currency.CurrencyExchangeAmount? = null
    ) {
        val currentConfig = _userConfig.value ?: return
        val newConfig = currentConfig.copy(
            gameConfig = currentConfig.gameConfig.copy(
                currencyExchangeConfig = currentConfig.gameConfig.currencyExchangeConfig.copy(
                    enabledSetting = enabledSetting ?: currentConfig.gameConfig.currencyExchangeConfig.enabledSetting,
                    currencyExchangeAmount = (currencyExchangeAmount?.name ?: currentConfig.gameConfig.currencyExchangeConfig.currencyExchangeAmount)
                )
            )
        )
        saveConfig(newConfig)
    }
    
    // 乱斗配置更新
    fun updateChaosWarConfig(
        enabledSetting: Boolean? = null,
        selectedTasks: List<String>? = null
    ) {
        val currentConfig = _userConfig.value ?: return
        val newConfig = currentConfig.copy(
            gameConfig = currentConfig.gameConfig.copy(
                chaosWarConfig = currentConfig.gameConfig.chaosWarConfig.copy(
                    enabledSetting = enabledSetting ?: currentConfig.gameConfig.chaosWarConfig.enabledSetting,
                    selectedTasks = (selectedTasks?.joinToString(",") ?: currentConfig.gameConfig.chaosWarConfig.selectedTasks)
                )
            )
        )
        saveConfig(newConfig)
    }
    
    // 门派邀请赛配置更新 - 包含5个好友的数值设置
    fun updateSectTournamentConfig(
        enabledSetting: Boolean? = null,
        setting1Value: String? = null,
        setting2Value: String? = null,
        setting3Value: String? = null,
        setting4Value: String? = null,
        setting5Value: String? = null
    ) {
        val currentConfig = _userConfig.value ?: return
        val newConfig = currentConfig.copy(
            gameConfig = currentConfig.gameConfig.copy(
                sectTournamentConfig = currentConfig.gameConfig.sectTournamentConfig.copy(
                    enabledSetting = enabledSetting ?: currentConfig.gameConfig.sectTournamentConfig.enabledSetting,
                    setting1Value = setting1Value ?: currentConfig.gameConfig.sectTournamentConfig.setting1Value,
                    setting2Value = setting2Value ?: currentConfig.gameConfig.sectTournamentConfig.setting2Value,
                    setting3Value = setting3Value ?: currentConfig.gameConfig.sectTournamentConfig.setting3Value,
                    setting4Value = setting4Value ?: currentConfig.gameConfig.sectTournamentConfig.setting4Value,
                    setting5Value = setting5Value ?: currentConfig.gameConfig.sectTournamentConfig.setting5Value
                )
            )
        )
        saveConfig(newConfig)
    }
    
    fun refreshAccount() {
        loadCurrentAccount()
    }
}
